from sqlalchemy.orm import sessionmaker

from api.models.api_models import SpeechFile


class SpeechFileDAO:
    def __init__(self, engine):
        self.engine = engine
        self.Session = sessionmaker(bind=self.engine, expire_on_commit=False)

    def create(self, speech_file_id, user_id, speech_file_path, synthesis_time=None):
        session = self.Session()
        speech_file = SpeechFile(speech_file_id=speech_file_id, user_id=user_id, speech_file_path=speech_file_path, synthesis_time=synthesis_time)
        session.add(speech_file)
        session.commit()
        session.close()
        return speech_file

    def read(self, speech_file_id):
        session = self.Session()
        speech_file = session.query(SpeechFile).filter_by(speech_file_id=speech_file_id).first()
        session.close()
        return speech_file

    def update(self, speech_file_id, user_id=None, speech_file_path=None, synthesis_time=None):
        session = self.Session()
        speech_file = session.query(SpeechFile).filter_by(speech_file_id=speech_file_id).first()
        if user_id is not None:
            speech_file.user_id = user_id
        if speech_file_path is not None:
            speech_file.speech_file_path = speech_file_path
        if synthesis_time is not None:
            speech_file.synthesis_time = synthesis_time
        session.commit()
        session.close()

    def delete(self, speech_file_id):
        session = self.Session()
        speech_file = session.query(SpeechFile).filter_by(speech_file_id=speech_file_id).first()
        session.delete(speech_file)
        session.commit()
        session.close()